<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Search Template | ElasticSearch 7.7 权威指南中文版</title>
	<meta name="keywords" content="ElasticSearch 权威指南中文版, elasticsearch 7, es7, 实时数据分析，实时数据检索" />
    <meta name="description" content="ElasticSearch 权威指南中文版, elasticsearch 7, es7, 实时数据分析，实时数据检索" />
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
	<link rel="stylesheet" type="text/css" href="../static/styles.css" />
	<script>
	var _link = 'search-template.html';
    </script>
</head>
<body>
<div class="main-container">
    <section id="content">
        <div class="content-wrapper">
            <section id="guide" lang="zh_cn">
                <div class="container">
                    <div class="row">
                        <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                            <div style="color:gray; word-break: break-all; font-size:12px;">原英文版地址: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.7/search-template.html" rel="nofollow" target="_blank">https://www.elastic.co/guide/en/elasticsearch/reference/7.7/search-template.html</a>, 原文档版权归 www.elastic.co 所有<br/>本地英文版地址: <a href="../en/search-template.html" rel="nofollow" target="_blank">../en/search-template.html</a></div>
                        <!-- start body -->
                  <div class="page_header">
<strong>重要</strong>: 此版本不会发布额外的bug修复或文档更新。最新信息请参考 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html" rel="nofollow">当前版本文档</a>。
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch Guide [7.7]</a></span>
»
<span class="breadcrumb-link"><a href="rest-apis.html">REST APIs</a></span>
»
<span class="breadcrumb-link"><a href="search.html">Search APIs</a></span>
»
<span class="breadcrumb-node">Search Template</span>
</div>
<div class="navheader">
<span class="prev">
<a href="clear-scroll-api.html">« Clear scroll API</a>
</span>
<span class="next">
<a href="multi-search-template.html">Multi Search Template »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="search-template"></a>Search Template<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h2>
</div></div></div>
<p>Allows you to use the mustache language to pre render search requests.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
    "source" : {
      "query": { "match" : { "{{my_field}}" : "{{my_value}}" } },
      "size" : "{{my_size}}"
    },
    "params" : {
        "my_field" : "message",
        "my_value" : "some message",
        "my_size" : 5
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1985.console"></div>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-template-api-request"></a>Request<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h3>
</div></div></div>
<p><code class="literal">GET _search/template</code></p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-template-api-desc"></a>Description<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The <code class="literal">/_search/template</code> endpoint allows you to use the mustache language to pre-
render search requests, before they are executed and fill existing templates
with template parameters.</p>
<p>For more information on how Mustache templating and what kind of templating you
can do with it check out the <a href="http://mustache.github.io/mustache.5.html" class="ulink" target="_top">online
documentation of the mustache project</a>.</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>The mustache language is implemented in Elasticsearch as a sandboxed scripting
language, hence it obeys settings that may be used to enable or disable scripts
per type and context as described in the
<a class="xref" href="modules-scripting-security.html#allowed-script-types-setting" title="Allowed script types setting">scripting docs</a>.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-template-api-path-params"></a>Path parameters<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
<code class="literal">&lt;index&gt;</code>
</span>
</dt>
<dd>
(Optional, string) Comma-separated list or wildcard expression of index names
used to limit the request.
</dd>
</dl>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-template-api-query-params"></a>Query parameters<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
<code class="literal">allow_no_indices</code>
</span>
</dt>
<dd>
<p>
(Optional, boolean) If <code class="literal">true</code>,
the request does <span class="strong strong"><strong>not</strong></span> return an error
if a wildcard expression
or <code class="literal">_all</code> value retrieves only missing or closed indices.
</p>
<p>This parameter also applies to <a class="xref" href="indices-aliases.html" title="Update index alias API">index aliases</a>
that point to a missing or closed index.</p>
<p>Defaults to <code class="literal">true</code>.</p>
</dd>
<dt>
<span class="term">
<code class="literal">ccs_minimize_roundtrips</code>
</span>
</dt>
<dd>
 (Optional, boolean) If <code class="literal">true</code>, network round-trips are minimized for
cross-cluster search requests. Defaults to <code class="literal">true</code>.
</dd>
<dt>
<span class="term">
<code class="literal">expand_wildcards</code>
</span>
</dt>
<dd>
<p>(Optional, string) Controls what kind of indices that wildcard expressions can
expand to. Multiple values are accepted when separated by a comma, as in
<code class="literal">open,hidden</code>. Valid values are:</p>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
<code class="literal">all</code>
</span>
</dt>
<dd>
Expand to open and closed indices, including <a class="xref" href="index-modules.html#index-hidden">hidden indices</a>.
</dd>
<dt>
<span class="term">
<code class="literal">open</code>
</span>
</dt>
<dd>
Expand only to open indices.
</dd>
<dt>
<span class="term">
<code class="literal">closed</code>
</span>
</dt>
<dd>
Expand only to closed indices.
</dd>
<dt>
<span class="term">
<code class="literal">hidden</code>
</span>
</dt>
<dd>
Expansion of wildcards will include <a class="xref" href="index-modules.html#index-hidden">hidden indices</a>.
Must be combined with <code class="literal">open</code>, <code class="literal">closed</code>, or both.
</dd>
<dt>
<span class="term">
<code class="literal">none</code>
</span>
</dt>
<dd>
Wildcard expressions are not accepted.
</dd>
</dl>
</div>
</dd>
<dt>
<span class="term">
<code class="literal">explain</code>
</span>
</dt>
<dd>
(Optional, boolean) If <code class="literal">true</code>, the response includes additional details about
score computation as part of a hit. Defaults to <code class="literal">false</code>.
</dd>
<dt>
<span class="term">
<code class="literal">ignore_throttled</code>
</span>
</dt>
<dd>
(Optional, boolean) If <code class="literal">true</code>, specified concrete, expanded or aliased indices
are not included in the response when throttled. Defaults to <code class="literal">false</code>.
</dd>
<dt>
<span class="term">
<code class="literal">ignore_unavailable</code>
</span>
</dt>
<dd>
(Optional, boolean) If <code class="literal">true</code>, missing or closed indices are not included in the
response. Defaults to <code class="literal">false</code>.
</dd>
<dt>
<span class="term">
<code class="literal">preference</code>
</span>
</dt>
<dd>
(Optional, string) Specifies the node or shard the operation should be
performed on. Random by default.
</dd>
<dt>
<span class="term">
<code class="literal">profile</code>
</span>
</dt>
<dd>
(Optional, boolean) If <code class="literal">true</code>, the query execution is profiled. Defaults
to <code class="literal">false</code>.
</dd>
<dt>
<span class="term">
<code class="literal">rest_total_hits_as_int</code>
</span>
</dt>
<dd>
(Optional, boolean) If <code class="literal">true</code>, <code class="literal">hits.total</code> are rendered as an integer in
the response. Defaults to <code class="literal">false</code>.
</dd>
<dt>
<span class="term">
<code class="literal">routing</code>
</span>
</dt>
<dd>
(Optional, string) Target the specified primary shard.
</dd>
<dt>
<span class="term">
<code class="literal">scroll</code>
</span>
</dt>
<dd>
(Optional, <a class="xref" href="common-options.html#time-units" title="Time units">time units</a>) Specifies how long a consistent view of
the index should be maintained for scrolled search.
</dd>
<dt>
<span class="term">
<code class="literal">search_type</code>
</span>
</dt>
<dd>
<p>
(Optional, string) The type of the search operation. Available options:
</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<code class="literal">query_then_fetch</code>
</li>
<li class="listitem">
<code class="literal">dfs_query_then_fetch</code>
</li>
</ul>
</div>
</dd>
<dt>
<span class="term">
<code class="literal">typed_keys</code>
</span>
</dt>
<dd>
(Optional, boolean) If <code class="literal">true</code>, aggregation and suggester names are
prefixed by their respective types in the response. Defaults to <code class="literal">false</code>.
</dd>
</dl>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-template-api-request-body"></a>Request body<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The API request body must contain the search definition template and its parameters.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="search-template-api-example"></a>Response codes<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="pre-registered-templates"></a>Store a search template<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>You can store a search template using the stored scripts API.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST _scripts/&lt;templateid&gt;
{
    "script": {
        "lang": "mustache",
        "source": {
            "query": {
                "match": {
                    "title": "{{query_string}}"
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1986.console"></div>
<p>The template can be retrieved by calling</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _scripts/&lt;templateid&gt;</pre>
</div>
<div class="console_widget" data-snippet="snippets/1987.console"></div>
<p>The API returns the following result:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
    "script" : {
        "lang" : "mustache",
        "source" : "{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}",
        "options": {
          "content_type" : "application/json; charset=UTF-8"
        }
    },
    "_id": "&lt;templateid&gt;",
    "found": true
}</pre>
</div>
<p>This template can be deleted by calling</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">DELETE _scripts/&lt;templateid&gt;</pre>
</div>
<div class="console_widget" data-snippet="snippets/1988.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="use-registered-templates"></a>Using a stored search template<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>To use a stored template at search time send the following request:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
    "id": "&lt;templateid&gt;", <a id="CO622-1"></a><i class="conum" data-value="1"></i>
    "params": {
        "query_string": "search for these words"
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1989.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO622-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>Name of the stored template script.</p>
</td>
</tr>
</table>
</div>
</div>

</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_validating_templates"></a>Validating a search template<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h3>
</div></div></div>
<p>A template can be rendered in a response with given parameters by using the
following request:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _render/template
{
  "source": "{ \"query\": { \"terms\": {{#toJson}}statuses{{/toJson}} }}",
  "params": {
    "statuses" : {
        "status": [ "pending", "published" ]
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1990.console"></div>
<p>The API returns the rendered template:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
  "template_output": {
    "query": {
      "terms": {
        "status": [ <a id="CO623-1"></a><i class="conum" data-value="1"></i>
          "pending",
          "published"
        ]
      }
    }
  }
}</pre>
</div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO623-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">status</code> array has been populated with values from the <code class="literal">params</code> object.</p>
</td>
</tr>
</table>
</div>
<p>Stored templates can also be rendered by calling the following request:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">GET _render/template/&lt;template_name&gt;
{
  "params": {
    "..."
  }
}</pre>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-template-explain-parameter"></a>Using the explain parameter<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>You can use the <code class="literal">explain</code> parameter when running a template:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
  "id": "my_template",
  "params": {
    "status": [ "pending", "published" ]
  },
  "explain": true
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1991.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-template-profile-parameter"></a>Profiling<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>You can use the <code class="literal">profile</code> parameter when running a template:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
  "id": "my_template",
  "params": {
    "status": [ "pending", "published" ]
  },
  "profile": true
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1992.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-template-query-string-single"></a>Filling in a query string with a single value<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
    "source": {
        "query": {
            "term": {
                "message": "{{query_string}}"
            }
        }
    },
    "params": {
        "query_string": "search for these words"
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1993.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-template-converting-to-json"></a>Converting parameters to JSON<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>The <code class="literal">{{#toJson}}parameter{{/toJson}}</code> function can be used to convert parameters
like maps and array to their JSON representation:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
  "source": "{ \"query\": { \"terms\": {{#toJson}}statuses{{/toJson}} }}",
  "params": {
    "statuses" : {
        "status": [ "pending", "published" ]
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1994.console"></div>
<p>which is rendered as:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
  "query": {
    "terms": {
      "status": [
        "pending",
        "published"
      ]
    }
  }
}</pre>
</div>
<p>A more complex example substitutes an array of JSON objects:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
    "source": "{\"query\":{\"bool\":{\"must\": {{#toJson}}clauses{{/toJson}} }}}",
    "params": {
        "clauses": [
            { "term": { "user" : "foo" } },
            { "term": { "user" : "bar" } }
        ]
   }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1995.console"></div>
<p>which is rendered as:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "query" : {
      "bool" : {
        "must" : [
          {
            "term" : {
                "user" : "foo"
            }
          },
          {
            "term" : {
                "user" : "bar"
            }
          }
        ]
      }
    }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-template-concatenate-array"></a>Concatenating array of values<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>The <code class="literal">{{#join}}array{{/join}}</code> function can be used to concatenate the
values of an array as a comma delimited string:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
  "source": {
    "query": {
      "match": {
        "emails": "{{#join}}emails{{/join}}"
      }
    }
  },
  "params": {
    "emails": [ "username@email.com", "lastname@email.com" ]
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1996.console"></div>
<p>which is rendered as:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "query" : {
        "match" : {
            "emails" : "username@email.com,lastname@email.com"
        }
    }
}</pre>
</div>
<p>The function also accepts a custom delimiter:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _search/template
{
  "source": {
    "query": {
      "range": {
        "born": {
            "gte"   : "{{date.min}}",
            "lte"   : "{{date.max}}",
            "format": "{{#join delimiter='||'}}date.formats{{/join delimiter='||'}}"
	    }
      }
    }
  },
  "params": {
    "date": {
        "min": "2016",
        "max": "31/12/2017",
        "formats": ["dd/MM/yyyy", "yyyy"]
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1997.console"></div>
<p>which is rendered as:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "query" : {
      "range" : {
        "born" : {
          "gte" : "2016",
          "lte" : "31/12/2017",
          "format" : "dd/MM/yyyy||yyyy"
        }
      }
    }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-template-default-values"></a>Default values<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>A default value is written as <code class="literal">{{var}}{{^var}}default{{/var}}</code> for instance:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
  "source": {
    "query": {
      "range": {
        "line_no": {
          "gte": "{{start}}",
          "lte": "{{end}}{{^end}}20{{/end}}"
        }
      }
    }
  },
  "params": { ... }
}</pre>
</div>
<p>When <code class="literal">params</code> is <code class="literal">{ "start": 10, "end": 15 }</code> this query would be rendered as:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "range": {
        "line_no": {
            "gte": "10",
            "lte": "15"
        }
  }
}</pre>
</div>
<p>But when <code class="literal">params</code> is <code class="literal">{ "start": 10 }</code> this query would use the default value
for <code class="literal">end</code>:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "range": {
        "line_no": {
            "gte": "10",
            "lte": "20"
        }
    }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-template-conditional-clauses"></a>Conditional clauses<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Conditional clauses cannot be expressed using the JSON form of the template.
Instead, the template <span class="strong strong"><strong>must</strong></span> be passed as a string.  For instance, let’s say
we wanted to run a <code class="literal">match</code> query on the <code class="literal">line</code> field, and optionally wanted
to filter by line numbers, where <code class="literal">start</code> and <code class="literal">end</code> are optional.</p>
<p>The <code class="literal">params</code> would look like:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "params": {
        "text":      "words to search for",
        "line_no": { <a id="CO624-1"></a><i class="conum" data-value="1"></i>
            "start": 10,
            "end":   20
        }
    }
}</pre>
</div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO624-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>The <code class="literal">line_no</code>, <code class="literal">start</code>, and <code class="literal">end</code> parameters are optional.</p>
</td>
</tr>
</table>
</div>
<p>When written as a query, the template would include invalid JSON, such as
section markers like <code class="literal">{{#line_no}}</code>:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
  "query": {
    "bool": {
      "must": {
        "match": {
          "line": "{{text}}" <a id="CO625-1"></a><i class="conum" data-value="1"></i>
        }
      },
      "filter": {
        {{#line_no}} <a id="CO625-2"></a><i class="conum" data-value="2"></i>
          "range": {
            "line_no": {
              {{#start}} <a id="CO625-3"></a><i class="conum" data-value="3"></i>
                "gte": "{{start}}" <a id="CO625-4"></a><i class="conum" data-value="4"></i>
                {{#end}},{{/end}} <a id="CO625-5"></a><i class="conum" data-value="5"></i>
              {{/start}}
              {{#end}} <a id="CO625-6"></a><i class="conum" data-value="6"></i>
                "lte": "{{end}}" <a id="CO625-7"></a><i class="conum" data-value="7"></i>
              {{/end}}
            }
          }
        {{/line_no}}
      }
    }
  }
}</pre>
</div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO625-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>Fill in the value of param <code class="literal">text</code></p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO625-2"><i class="conum" data-value="2"></i></a></p>
</td>
<td align="left" valign="top">
<p>Include the <code class="literal">range</code> filter only if <code class="literal">line_no</code> is specified</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO625-3"><i class="conum" data-value="3"></i></a></p>
</td>
<td align="left" valign="top">
<p>Include the <code class="literal">gte</code> clause only if <code class="literal">line_no.start</code> is specified</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO625-4"><i class="conum" data-value="4"></i></a></p>
</td>
<td align="left" valign="top">
<p>Fill in the value of param <code class="literal">line_no.start</code></p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO625-5"><i class="conum" data-value="5"></i></a></p>
</td>
<td align="left" valign="top">
<p>Add a comma after the <code class="literal">gte</code> clause only if <code class="literal">line_no.start</code>
AND <code class="literal">line_no.end</code> are specified</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO625-6"><i class="conum" data-value="6"></i></a></p>
</td>
<td align="left" valign="top">
<p>Include the <code class="literal">lte</code> clause only if <code class="literal">line_no.end</code> is specified</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO625-7"><i class="conum" data-value="7"></i></a></p>
</td>
<td align="left" valign="top">
<p>Fill in the value of param <code class="literal">line_no.end</code></p>
</td>
</tr>
</table>
</div>
<p>Because search templates cannot include invalid JSON, you can pass the same
query as a string instead:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"source": "{\"query\":{\"bool\":{\"must\":{\"match\":{\"line\":\"{{text}}\"}},\"filter\":{{{#line_no}}\"range\":{\"line_no\":{{{#start}}\"gte\":\"{{start}}\"{{#end}},{{/end}}{{/start}}{{#end}}\"lte\":\"{{end}}\"{{/end}}}}{{/line_no}}}}}}"</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="search-template-encode-urls"></a>Encoding URLs<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/search/search-template.asciidoc">edit</a>
</h4>
</div></div></div>
<p>The <code class="literal">{{#url}}value{{/url}}</code> function can be used to encode a string value
in a HTML encoding form as defined in by the
<a href="http://www.w3.org/TR/html4/" class="ulink" target="_top">HTML specification</a>.</p>
<p>As an example, it is useful to encode a URL:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET _render/template
{
    "source" : {
        "query" : {
            "term": {
                "http_access_log": "{{#url}}{{host}}/{{page}}{{/url}}"
            }
        }
    },
    "params": {
        "host": "https://www.elastic.co/",
        "page": "learn"
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/1998.console"></div>
<p>The previous query will be rendered as:</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
    "template_output" : {
        "query" : {
            "term" : {
                "http_access_log" : "https%3A%2F%2Fwww.elastic.co%2F%2Flearn"
            }
        }
    }
}</pre>
</div>
</div>

</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="clear-scroll-api.html">« Clear scroll API</a>
</span>
<span class="next">
<a href="multi-search-template.html">Multi Search Template »</a>
</span>
</div>
</div>

                  <!-- end body -->
                        </div>
                        <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                        
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </section>
</div>
<script src="../static/cn.js"></script>
</body>
</html>